<template>
  <div class="face-container">
    <div class="login-mid-mid">
        <!--捕获人脸区域-->
        <div class="videoCamera-canvasCamera">
          <video
            id="videoCamera"
            :width="srcObj.videoWidth"
            :height="srcObj.videoHeight"
            autoplay
          ></video>
          <canvas
            style="display: none"
            id="canvasCamera"
            :width="srcObj.videoWidth"
            :height="srcObj.videoHeight"
          ></canvas>

          <!--人脸特效区域-->
          <div v-if="srcObj.faceImgState" class="face-special-effects-2"></div>
          <div v-else class="face-special-effects"></div>
        </div>

        <!--按钮区域-->
        <div class="face-btn">
          <el-button @click="faceVef()" :disabled="srcObj.faceImgState">
            {{ srcObj.faceImgState ? "正在识别中..." : "开始识别" }}
          </el-button>
        </div>

        <!--消息区域-->
        <div class="msg" v-if="isShowMsg">
          <div class="server-msg">{{ srcObj.msg }}</div>
          <div class="welcome">Welcome to face recognition</div>
        </div>

      </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect } from "vue";
import { useRouter } from 'vue-router'
// types
import { IOption, ISrcObj } from '@/types/Camera/cameraOptionType'
// api
import loginAPI from '@/request/api/login'
import retrievePwdApi from "@/request/api/retrievePwd";
// camera
import $camera from "@/camera"
// msg
import { showMessageBox, showNotification } from '@/utils/alertMsg';
// store
import useLoginStore from "@/store/login";
import useForgetPwd from "@/store/forgetPwd";
import { storeToRefs } from 'pinia';

const forgetPwdStore = useForgetPwd();
const {
  userInfo
} = storeToRefs(forgetPwdStore);

const loginStore = useLoginStore();
const router = useRouter();

// data
const srcObj = reactive<ISrcObj>({
  videoWidth: 200,
  videoHeight: 200,
  msg: "",
  faceImgState: false,
});

// 传递的camera参数
let faceOption = ref<IOption>({
  videoWidth: 0,
  videoHeight: 0,
  thisCanvas: null,
  thisContext: null,
  thisVideo: null,
  canvasId: '',
  videoId: ''
});

// 接收props
const props = defineProps({
  isCameraOpen: {
    type: Boolean
  },
  isShowMsg: {
    type: Boolean,
    default: () => true
  },
  isVerifyType: {
    type: Boolean,
    default: () => false
  }
});

watchEffect(() => {
  if(props.isCameraOpen) {
    //调用摄像头
    faceOption.value = $camera.getCamera({
        videoWidth: 200,
        videoHeight: 200,
        thisCanvas: null,
        thisContext: null,
        thisVideo: null,
        canvasId: "canvasCamera",
        videoId: "videoCamera",
    });
  }
  if(!props.isCameraOpen && faceOption.value.thisVideo) {
    // @ts-ignore
    faceOption.value.thisVideo.srcObject.getTracks()[0].stop();
  }
});

// 验证人脸函数
const faceVef = () => {

  // 开始绘制图片
  // console.log("faceOption.value", faceOption.value);
  let imageBase = $camera.draw(faceOption.value);
  if (srcObj.faceImgState) {
    return;
  }
  srcObj.faceImgState = true;
  if (imageBase === "" || imageBase === null || imageBase === undefined) {
    alert("图片数据为空");
  } else {
    /* 老方法============================================ 
      loginAPI.loginByFace({ imageBase }).then((res: any) => {
        // console.log('res', res)
        srcObj.faceImgState = false
        // 跳转首页
        if (res.code === 200) {
          showMessageBox("success", `登录成功!${res.msg}`);
        } else {
          showMessageBox("error", `登录失败${res.msg}`);
        }
        // 关闭摄像头
        // @ts-ignore
        faceOption.value.thisVideo.srcObject.getTracks()[0].stop();
      })
    */
    
    if(props.isVerifyType) {
      const params = {
        phone: userInfo.value.phone,
        username: userInfo.value.username,
        imageBase: imageBase
      }
      retrievePwdApi.checkUserFace(params).then((res: any) => {
        if (res.code === 200) {
          showNotification("success", 'success√', `${res.msg}`);
          showMessageBox("success", "可点击下一步进行操作了哦");
          forgetPwdStore.setVerifySuccess(true);
          // 关闭摄像头
          // @ts-ignore
          faceOption.value.thisVideo.srcObject.getTracks()[0].stop();
        } else {
          showMessageBox("error", `${res.msg}`);
          forgetPwdStore.setVerifySuccess(false);
        }
      }).finally(() => {
        srcObj.faceImgState = false;
      });
    } else {
      // 新接口
      const params = {
        phone: '',
        password: '',
        imageBase: imageBase
      }
      loginAPI.useLogin(params).then((res: any) => {
        // 跳转首页
        if (res.code === 200) {
          showMessageBox("success", `${res.msg}`);
          loginStore.setToken(res.data.token);
          // 关闭摄像头
          // @ts-ignore
          faceOption.value.thisVideo.srcObject.getTracks()[0].stop();
          // 跳转到首页
          setTimeout(() => {
            router.replace("/home");
            // window.location.href = "/home";
          }, 100)
        } else {
          showMessageBox("error", `登录失败, ${res.msg}`);
        }
      }).finally(() => {
        srcObj.faceImgState = false;
      });
    }
   
    // 关闭摄像头
    // @ts-ignore
    // faceOption.value.thisVideo.srcObject.getTracks()[0].stop();
  }
};

</script>

<style scoped lang="scss">
.login-mid-mid{
    width: 100%;
    height: 80%;
}
.videoCamera-canvasCamera{
    position: relative;
    width: 200px;
    height: 200px;
    margin: 0 auto;
}
.face-special-effects,.face-special-effects-2{
    width:  300px;
    height: 300px;
    position: absolute;
    z-index: 99999999999!important;
    transform: translate(-50%,-50%);
    top: 50%;
    left: 50%;
}
.face-special-effects{
    background: url('@/assets/images/login/face.gif') no-repeat;
    background-size: 300px 300px;
}
.face-special-effects-2{
    background: url('@/assets/images/login/face_detection.gif') no-repeat;
    background-size: 300px 300px;
}
.face-btn{
    width: 100%;
    height: 50px;
    z-index: 999999999999!important;
    margin-top: 45px;
    text-align: center;
}
.face-btn button{
    background-color: #5ed38f;
    border: none;
    outline: none;
    width: 200px;
    height: 40px;
    border-radius: 6px;
    color: #ffffff;
    cursor: pointer;
    transition: all 0.3s ease;
    &:hover {
      background-color: #0ae678;
    }
}
.msg{
    width: 100%;
    height: 75px;
    // border: 1px solid black;
}
.server-msg{
    width: 100%;
    height: 35px;
    text-align: center;
    line-height: 35px;
    color: #000000;
}
.welcome{
    width: 100%;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 20px;
    font-family: "Baskerville Old Face";
}
</style>